package com.ninth_group.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
public class RedisSerializerUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private final ObjectMapper mapper = new ObjectMapper();

    /**
     * 将对象序列化成json串
     * @param key key
     * @param obj value
     */
    public <T> void set(String key, T obj, long timeout, TimeUnit unit)
            throws JsonProcessingException {
        String s = mapper.writeValueAsString(obj);
        stringRedisTemplate.opsForValue().set(key, s, timeout, unit);
    }

    // ==== 新增：支持 TypeReference + TTL 的 set 方法 ====
    public <T> void set(String key, TypeReference<T> obj,
                        long timeout, TimeUnit unit) throws JsonProcessingException {
        String s = mapper.writeValueAsString(obj);
        stringRedisTemplate.opsForValue().set(key, s, timeout, unit);
    }

    /**
     * 将json串反序列化成对象
     * @param key key
     * @param clazz 对象类字节码
     * @return 对象
     */
    public <T> T get(String key, Class<T> clazz) throws JsonProcessingException {
        String s = stringRedisTemplate.opsForValue().get(key);
        if (s == null || s.isEmpty()) return null;
        return mapper.readValue(s, clazz);
    }

    /**
     * 将json串反序列化成对象列表
     * @param key key
     * @param elementType 列表元素类型
     * @return 对象列表
     * @param <T> 泛型类型
     * @throws JsonProcessingException 异常
     */
    public <T> List<T> getList(String key, Class<T> elementType)
            throws JsonProcessingException {
        String json = stringRedisTemplate.opsForValue().get(key);
        if (json == null || json.isEmpty()) {
            return Collections.emptyList();
        }
        return mapper.readValue(json,
                mapper.getTypeFactory().
                        constructCollectionType(List.class, elementType)
        );
    }

    // 新增方法，支持通过 TypeReference 反序列化泛型类型
    public <T> T get(String key, TypeReference<T> typeReference) throws JsonProcessingException {
        String s = stringRedisTemplate.opsForValue().get(key);
        if (s == null || s.isEmpty()) return null;
        return mapper.readValue(s, typeReference);
    }

    /**
     * 删除key
     * @param key key
     */
    public void delete(String... key) {
        for (String s : key) {
            stringRedisTemplate.delete(s);
        }
    }

}
